package com.atguigu.upp.mapper;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;

/**
 * Created by Smexy on 2022/10/16
 */
public interface ClickhouseMapper
{

    /*
            建表
            ${xx}:  原汁原味
            #{xx}:  自动根据类型，拼接单引号
     */
    @Update(" create table if not exists  ${table}(uid String, ${column} )engine=MergeTree order by (uid)")
    void createWideTable(@Param("table") String table, @Param("column") String column);

    @Update(" drop table if exists ${table} ")
    void dropWideTable(@Param("table") String table);

    /*
  insert into user_tag_value_string
select
    -- 防止某些数字类型在宽表中没有值，是使用空字符串存储
    col.1,if(col.2 = '',0,col.2) tagValue ,groupBitmapState(uid),
from
    (
        select
          uid,
        arrayJoin([
        -- 当天的宽表有几个标签列，标签列的名是什么
            ('gender', gender),
            ('agegroup', agegroup),
            ('favor', favor)
            ]) col
        from user_tag_merge
        -- 某些同学宽表中有 uid = null的脏数据
        where length(uid) > 0
    ) t1
group by col.1,col.2;
     */
    //从宽表中计算每个分群的bitmap写入
    @Insert(" insert into ${table}  " +
            " select col.1,if(col.2 = '','0',col.2) tagValue , groupBitmapState(toUInt64(uid)) ,#{dt}  from( " +
            "   select   uid, arrayJoin( [ ${ tags }  ]  ) col   from  ${source}  where length(uid) > 0 ) t1 " +
            " group by col.1,col.2;  "
    )
    void insertBitmap(@Param("table") String table,@Param("tags") String tags,@Param("source") String sourceTable,@Param("dt")String doDate);

    //为了保证幂等性，先删除今天已经导入的分区，再写入新的数据
    @Update(" alter table ${table} delete where dt = #{dt} ")
    void deleteOldPartitionData(@Param("table") String table,@Param("dt") String doDate);
}
